<template>
  <div ref="containerRef" style="position: relative;">
    <div ref="chartRef" id="charts" style="width: 600px; height: 400px;"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import * as echarts from 'echarts'

let myChart = null
const chartRef = ref(null)
const initChart = () => {
  myChart = echarts.init(chartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      // data: ['曲线1', '曲线2', '曲线3', '曲线4']
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '曲线1',
        type: 'line',
        smooth: false,
        showSymbol: false,
        id: '曲线1id:123445613513',
        data: [120, 132, 101, 134, 90, 230, 210]
      },
      {
        name: '曲线2',
        type: 'line',
        smooth: false,
        showSymbol: false,
        id: '曲线2id:9994646456',
        data: [220, 182, 191, 234, 290, 330, 310]
      },
      {
        name: '曲线3',
        type: 'line',
        smooth: false,
        showSymbol: false,
        data: [150, 232, 201, 154, 190, 330, 410]
      },
      {
        name: '曲线4',
        type: 'line',
        smooth: false,
        showSymbol: false,
        tooltip: {
          valueFormatter: function (value) {
            return value + '家'
          }
        },
        data: [180, 211, 241, 254, 290, 330, 410]
      }
    ]
  }

  myChart.setOption(option)
  // 工具函数：计算点到线段的距离
  let pointToSegmentDistance = (px, py, x1, y1, x2, y2) => {
    let A = px - x1
    let B = py - y1
    let C = x2 - x1
    let D = y2 - y1

    let dot = A * C + B * D
    let len_sq = C * C + D * D
    let param = -1
    if (len_sq !== 0)
      // in case of 0 length line
      param = dot / len_sq

    let xx, yy

    if (param < 0) {
      xx = x1
      yy = y1
    } else if (param > 1) {
      xx = x2
      yy = y2
    } else {
      xx = x1 + param * C
      yy = y1 + param * D
    }

    let dx = px - xx
    let dy = py - yy
    return Math.sqrt(dx * dx + dy * dy)
  }
  // 监听容器点击事件
  document.getElementById('charts').onclick = e => {
    let pointInPixel = [e.offsetX, e.offsetY]
    let xAxis = option.xAxis.data
    let series = option.series
    // 转换像素坐标到数据坐标
    let pointInGrid = myChart.convertFromPixel({ seriesIndex: 0 }, pointInPixel)
    if (!pointInGrid) return
    let xValue = pointInGrid[0]
    let yValue = pointInGrid[1]

    // 因为x轴是category类型，xValue是类别索引附近的数字，四舍五入取整
    let xIndex = Math.round(xValue)

    // 计算点击点对应的像素坐标（用于距离计算）
    let px = e.offsetX
    let py = e.offsetY
    // 设置一个距离阈值，单位是像素
    let threshold = 3
    // 遍历每条曲线，判断点击点是否靠近曲线
    for (let i = 0; i < series.length; i++) {
      let data = series[i].data
      // 遍历曲线的每条线段
      for (let j = 0; j < data.length - 1; j++) {
        // 获取线段两个端点的像素坐标
        let p1 = myChart.convertToPixel({ seriesIndex: i }, [j, data[j]])
        let p2 = myChart.convertToPixel({ seriesIndex: i }, [j + 1, data[j + 1]])
        let dist = pointToSegmentDistance(px, py, p1[0], p1[1], p2[0], p2[1])
        if (dist <= threshold) {
          // 找到点击的曲线和线段
          console.log(`你点击了${series[i]}曲线，线段[${xAxis[j]} - ${xAxis[j + 1]}]附近--点击的位置x${px}-y轴${py}`, series[i])
          return
        }
      }
    }
  }
}

onMounted(() => {
  initChart()
})

onBeforeUnmount(() => {
  if (myChart) {
    myChart.dispose()
  }
})
</script>